package com.umer.pinban;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.bean.UserInfo;
import com.common.db.UserDao;
import com.common.okhttp.OkEntityRequest;
import com.common.permission.RxPermissions;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.brvah.BaseQuickAdapter;
import com.common.ui.recycleview.decoration.DividerGridItemDecoration;
import com.common.utils.AntiShake;
import com.common.utils.Constants;
import com.common.utils.EventConstants;
import com.common.utils.GlideUtils;
import com.common.utils.MD5Utils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.umer.pinban.action.ActionActivity;
import com.umer.pinban.adapter.home.HomeAdapter;
import com.umer.pinban.base.BasicActivity;
import com.umer.pinban.bean.home.HomeBean;
import com.umer.pinban.bean.user.SelectShopInfoBean;
import com.umer.pinban.customer.AddCustomerActivity;
import com.umer.pinban.customer.CustomerManagerActivity;
import com.umer.pinban.customerpinglun.CustomerPingLunActivity;
import com.umer.pinban.datafenxi.DataFenXiActivity;
import com.umer.pinban.fenxi.FenXiActivity;
import com.umer.pinban.gongzijisuan.GongZiJiSuanActivity;
import com.umer.pinban.huiyiguanli.HuiYiGuanLiActivity;
import com.umer.pinban.inventorymanagement.InventoryManagementActivity;
import com.umer.pinban.jinrizongjie.JinRiZongJieActivity;
import com.umer.pinban.kaoqin.KaoQinActivity;
import com.umer.pinban.mendianshouzhi.MenDianShouZhiActivity;
import com.umer.pinban.mendianyujin.MenDianYuJinActivity;
import com.umer.pinban.renwuguanli.RenWuGuanLiActivity;
import com.umer.pinban.scan.ScanCodeActivity;
import com.umer.pinban.scan.ScanManagerCode;
import com.umer.pinban.shangpingguanli.ShangPingGuanLiActivity;
import com.umer.pinban.staff.StaffManagerActivity;
import com.umer.pinban.tiyankeguanli.TiYanKeGuanLiActivity;
import com.umer.pinban.user.LoginActivity;
import com.umer.pinban.user.UserActivity;
import com.umer.pinban.yuyue.YuYueActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import me.devilsen.czxing.Scanner;
import me.devilsen.czxing.code.BarcodeFormat;
import me.devilsen.czxing.view.ScanActivityDelegate;

public class HomeActivity extends BasicActivity {

    @BindView(R.id.recycleview)
    RecyclerView recycleview;
    @BindView(R.id.iv_head)
    RoundedImageView ivHead;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    private List<HomeBean> infos = new ArrayList<>();
    private HomeAdapter homeAdapter;
    private RxPermissions rxPermissions;
    private UserInfo userInfo;
    private UserDao userDao;

    @Override
    public boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                //是否可以修改导航栏颜色，默认为true
                .navigationBarEnable(true)
                //导航栏颜色，不写默认黑色
                .navigationBarColor(R.color.barcolor)
                .statusBarColor(R.color.md_red_800)
                //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .fitsSystemWindows(true)
                .init();
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return null;
    }

    @Override
    public boolean isSupportSwipeBackEnabled() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_home;
    }

    @Override
    protected void onResume() {
        if(AppHolder.getInstance().getFlag()==1){
            AppHolder.getInstance().setFlag(0);
            relogin();
        }
        /**
         * 设置为横屏
         */
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onResume();
    }

    @Override
    public void init() {
        userDao = new UserDao(this);
        rxPermissions = new RxPermissions(this);
        userInfo = AppHolder.getInstance().getUserInfo();
        if (userInfo != null) {
            GlideUtils.getInstance().loadHeadImageView(this,
                    Constants.IP_PORT_DEFAULT_PICTURE + userInfo.getHeader(), ivHead);
        }
        for (int i = 0; i < 18; i++) {
            HomeBean homeBean = new HomeBean();
            if (i == 0) {
                homeBean.setRes(R.drawable.res1);
            } else if (i == 1) {
                homeBean.setRes(R.drawable.res2);
            } else if (i == 2) {
                homeBean.setRes(R.drawable.res3);
            } else if (i == 3) {
                homeBean.setRes(R.drawable.res4);
            } else if (i == 4) {
                homeBean.setRes(R.drawable.res5);
            } else if (i == 5) {
                homeBean.setRes(R.drawable.res6);
            } else if (i == 6) {
                homeBean.setRes(R.drawable.res7);
            } else if (i == 7) {
                homeBean.setRes(R.drawable.res8);
            } else if (i == 8) {
                homeBean.setRes(R.drawable.res9);
            } else if (i == 9) {
                homeBean.setRes(R.drawable.res10);
            }else if (i == 10) {
                homeBean.setRes(R.drawable.res11);
            }else if (i == 11) {
                homeBean.setRes(R.drawable.res12);
            }else if (i == 12) {
                homeBean.setRes(R.drawable.res13);
            }else if (i == 13) {
                homeBean.setRes(R.drawable.res14);
            }else if (i == 14) {
                homeBean.setRes(R.drawable.res15);
            }else if (i == 15) {
                homeBean.setRes(R.drawable.res16);
            }else if (i == 16) {
                homeBean.setRes(R.drawable.res17);
            }else if (i == 17) {
                homeBean.setRes(R.drawable.res18);
            }
            infos.add(homeBean);
        }
        homeAdapter = new HomeAdapter(R.layout.item_home, infos);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 6);
        recycleview.setLayoutManager(gridLayoutManager);
        recycleview.addItemDecoration(new DividerGridItemDecoration(this));
        recycleview.setAdapter(homeAdapter);
        recycleview.setOverScrollMode(View.OVER_SCROLL_NEVER);
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //会员添加
                if (position == 0) {
                    Intent intent = new Intent(HomeActivity.this, AddCustomerActivity.class);
                    intent.putExtra("personnelId", -1);
                    intent.putExtra("personneName", "");
                    startActivity(intent);
                }
                //会员管理
                else if (position == 1) {
                    switchTo(HomeActivity.this, CustomerManagerActivity.class, false);
                }
                //体验客管理
                else if (position == 2) {
                    switchTo(HomeActivity.this, TiYanKeGuanLiActivity.class, false);
                }
                //商品管理
                else if (position == 3) {
                    switchTo(HomeActivity.this, ShangPingGuanLiActivity.class, false);
                }
                //工资计算
                else if (position == 4) {
                    switchTo(HomeActivity.this, GongZiJiSuanActivity.class, false);
                }
                //预约
                else if (position == 5) {
                    switchTo(HomeActivity.this, YuYueActivity.class, false);
                }
                //数据分析
                else if (position == 6) {
                    switchTo(HomeActivity.this, DataFenXiActivity.class, false);
                }
                //深度分析
                else if (position == 7) {
                    switchTo(HomeActivity.this, FenXiActivity.class, false);
                }
                //客户评论
                else if (position == 8) {
                    switchTo(HomeActivity.this, CustomerPingLunActivity.class, false);
                }
                //员工管理
                else if (position == 9) {
                    switchTo(HomeActivity.this, StaffManagerActivity.class, false);
                }
                //营销活动
                else if (position == 10) {
                    switchTo(HomeActivity.this, ActionActivity.class, false);
                }
                //会议管理
                else if (position == 11) {
                    switchTo(HomeActivity.this, HuiYiGuanLiActivity.class, false);
                }
                //今日总结
                else if (position == 12) {
                    switchTo(HomeActivity.this, JinRiZongJieActivity.class, false);
                }
                //考勤
                else if (position == 13) {
                    switchTo(HomeActivity.this, KaoQinActivity.class, false);
                }
                //门店收支
                else if (position == 14) {
                    switchTo(HomeActivity.this, MenDianShouZhiActivity.class, false);
                }
                //库存管理
                else if (position == 15) {
                    switchTo(HomeActivity.this, InventoryManagementActivity.class, false);
                }
                //门店预警
                else if (position == 16) {
                    switchTo(HomeActivity.this, MenDianYuJinActivity.class, false);
                }
                //任务管理
                else if (position == 17) {
                    switchTo(HomeActivity.this, RenWuGuanLiActivity.class, false);
                }
            }
        });
    }

    @Override
    public void loadData() {
        relogin();
    }

    @OnClick({R.id.iv_head,R.id.tv_search, R.id.iv_scan})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                //判断是否多次点击
                if (AntiShake.check(view.getId())) {
                    return;
                }
                switchTo(HomeActivity.this, UserActivity.class,false);
                break;
            case R.id.tv_search:
                //判断是否多次点击
                if (AntiShake.check(view.getId())) {
                    return;
                }
                break;
            case R.id.iv_scan:
                //判断是否多次点击
                if (AntiShake.check(view.getId())) {
                    return;
                }
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> {
                            if (permission.granted) {
                                // permission.name 权限被授予
                                //openScan();
                                openScanCode();
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // permission.name 权限拒绝许可
                                showToast(" 权限拒绝");
                            } else {
                                // permission.name权限拒绝并不再提醒
                                // 需要进入设置
                                goIntentSetting();
                            }
                        });
                break;
            default:
                break;
        }
    }

    @Override
    public void handlerMeg(MsgBean msgBean) {
        super.handlerMeg(msgBean);
        int flag = msgBean.getFlag();
        if(flag == EventConstants.pay_sucess){
        }else if(flag == EventConstants.update_user_sucess){
            selectShopInfo();
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        switch (what) {
            case R.id.login:
                UserInfo userInfo = (UserInfo) t.getT();
                AppHolder.getInstance().setUserInfo(userInfo);
                userDao.deleteAll();
                userDao.add(userInfo);
                break;
            case R.id.selectShopInfo:
                SelectShopInfoBean selectShopInfoBean = (SelectShopInfoBean) t.getT();
                if(selectShopInfoBean!=null){
                    AppHolder.getInstance().getUserInfo().setHeader(selectShopInfoBean.getHeader());
                    userDao.update(AppHolder.getInstance().getUserInfo());
                    GlideUtils.getInstance().loadHeadImageView(this,
                            Constants.IP_PORT_DEFAULT_PICTURE + selectShopInfoBean.getHeader(), ivHead);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    public void openScan() {
        Resources resources = getResources();
        List<Integer> scanColors = Arrays.asList(getColor(this, R.color.md_red_800),
                getColor(this, R.color.md_red_800), getColor(this, R.color.md_red_800));
        Scanner.with(this)
                .setBorderColor(getColor(this, R.color.md_red_800))
                .setCornerColor(getColor(this, R.color.md_red_800))
                .setScanLineColors(scanColors)
                .setOnClickAlbumDelegate(new ScanActivityDelegate.OnClickAlbumDelegate() {
                    @Override
                    public void onClickAlbum(Activity activity) {
                    }

                    @Override
                    public void onSelectData(int requestCode, Intent data) {
                    }
                })
                .setOnScanResultDelegate(new ScanActivityDelegate.OnScanDelegate() {
                    @Override
                    public void onScanResult(Activity activity, String result, BarcodeFormat format) {
                        switchTo(HomeActivity.this, LoginActivity.class, false);
                    }
                })
                .start();
    }

    public void openScanCode() {
        List<Integer> scanColors = Arrays.asList(getColor(this, R.color.md_red_800),
                getColor(this, R.color.md_red_800), getColor(this, R.color.md_red_800));
        ScanManagerCode scanManagerCode = new ScanManagerCode(this);
        scanManagerCode.setBorderColor(getColor(this, R.color.md_red_800))
                .setCornerColor(getColor(this, R.color.md_red_800))
                .setFlashLightOffDrawable(R.drawable.flashlight_clode)
                .setFlashLightOnDrawable(R.drawable.flashlight_open)
                .showAlbum(false)
                .setScanLineColors(scanColors);
        Intent intent = new Intent(this, ScanCodeActivity.class);
        intent.putExtra("option", scanManagerCode.getScanOption());
        startActivity(intent);
    }

    private void relogin(){
        UserInfo bean = userDao.query();
        OkEntityRequest<UserInfo> request = new OkEntityRequest<>(R.id.login,
                Constants.USER_LOGIN, UserInfo.class);
        request.addParams("phone", bean.getPhone());
        request.addParams("password",getMD5(bean.getPassword()));
        requestOkhttpEntity(request);
    }

    private String getMD5(String val) {
        return getString(MD5Utils.getInstance().toMD5(val));
    }

    private String getString(String val) {
        if (!TextUtils.isEmpty(val)) {
            String firstPart = val.substring(0, 2);
            String twoPart = val.substring(2, val.length());
            return twoPart + firstPart;
        }
        return "";
    }

    private void selectShopInfo(){
        OkEntityRequest<SelectShopInfoBean> request = new OkEntityRequest<>(R.id.selectShopInfo,
                Constants.selectShopInfo, SelectShopInfoBean.class);
        request.addParams("shopId", userInfo.getShopId());
        request.setHeader(true);
        requestOkhttpEntity(request);
    }
}
